import dayjs from "dayjs";
import {
  getFirmwareListApi,
  SearchFirmwareParams,
  UploadFirmwareParams,
  uploadFirmwareApi,
  deleteFirmwareApi,
} from "@/api/firmware";
import {ElMessage} from "element-plus";
import {type PaginationProps} from "@pureadmin/table";
import {reactive, ref, onMounted, toRaw} from "vue";
import {Result} from "@/api/common/response";

export function useFirmwareHooks() {
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  //添加设备类型dialog相关
  const dialogVisible = ref(false);

  const searchFormParams = reactive<SearchFirmwareParams>({});

  //文件上传相关
  const FileUploadParams: UploadFirmwareParams = reactive({
    version: null,
    remark: null,
    uploadUser: null
  });
  // @ts-ignore
  //data保存文件对象
  const fileData = ref({
    data: null
  });
  //文件提交上传方法
  const uploadFileFunction = async () => {
    const formData = new FormData();
    formData.append("file", fileData.value.data.raw);
    // @ts-ignore
    formData.append(
      "firmware",
      new Blob([JSON.stringify(FileUploadParams)], {type: "application/json"})
    );
    const res: Result = await uploadFirmwareApi(formData);
    if (res.code === 200) {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      await getFirmwareList();
    } else {
      ElMessage.error("添加失败");
    }
  };

  //删除固件方法
  const deleteFirmwareFunction = async (firmwareId: number) => {
    const res: Result = await deleteFirmwareApi(firmwareId);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      await getFirmwareList();
    }else {
      ElMessage.error("删除失败");
    }
  };
  //上传固件点击按钮触发逻辑
  const uploadFirmwareButton = (formEl, uploadForm) => {
    //这个uploadForm不传element plus表单的resetFields就会报错，bug
    if (formEl) {
      formEl.resetFields();
    }
    if (uploadForm) {
      uploadForm.clearFiles();
    }
    dialogVisible.value = true;
    fileData.value.data = {};
  };

  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "id",
      minWidth: 100
    },
    {
      label: "版本",
      prop: "version",
      minWidth: 100
    },
    {
      label: "固件描述",
      prop: "remark",
      minWidth: 100
    },
    {
      label: "上传者",
      prop: "uploadUser",
      minWidth: 100
    },
    {
      label: "上传时间",
      prop: "createAt",
      minWidth: 100,
      formatter: ({createTime}) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];

  async function onSearch() {
    // 点击搜索的时候 需要重置分页
    pagination.currentPage = 1;
    getFirmwareList();
  }

  async function getFirmwareList() {
    try {
      loading.value = true;
      searchFormParams.pageSize  = pagination.pageSize;
      searchFormParams.pageNum = pagination.currentPage;
      // @ts-ignore
      const {data} = await getFirmwareListApi(toRaw(searchFormParams));
      dataList.value = data.list;
      pagination.total = data.total;
    } catch (e) {
      console.error(e);
      // ElMessage.warning((e as Error)?.message || "加载失败");
    } finally {
      loading.value = false;
    }
  }

  const resetForm = async formEl => {
    if (!formEl) return;
    formEl.resetFields();
    await getFirmwareList();
  };


  onMounted(async () => {
    await getFirmwareList();
  });


  return {
    loading,
    columns,
    dataList,
    pagination,
    searchFormParams,
    resetForm,
    dialogVisible,
    FileUploadParams,
    FileList,
    uploadFileFunction,
    fileData,
    uploadFirmwareButton,
    deleteFirmwareFunction,
    onSearch
  };
}
